package top.frsf.mqtt.handler.strategy;

import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.mqtt.MqttMessage;
import io.netty.handler.codec.mqtt.MqttMessageType;
import io.netty.handler.codec.mqtt.MqttSubscribeMessage;
import io.netty.handler.codec.mqtt.MqttTopicSubscription;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import top.frsf.mqtt.handler.strategy.abs.MqttMessageHandlerStrategy;
import top.frsf.mqtt.session.SessionManager;

/**
 * MQTT协议事件 - 订阅事件处理器
 *
 * @author He Kuntao
 * @since 2025/5/29 16:01
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class SubscribeMessageHandler implements MqttMessageHandlerStrategy {

    private final SessionManager sessionManager;

    @Override
    public void handle(ChannelHandlerContext ctx, MqttMessage message) {
        MqttSubscribeMessage msg = (MqttSubscribeMessage) message;
        String clientId = sessionManager.getClientIdByChannel(ctx.channel());
        if (clientId == null) {
            ctx.close();
            return;
        }

        // 处理订阅
        for (MqttTopicSubscription sub : msg.payload().topicSubscriptions()) {
            String topic = sub.topicName();
            sessionManager.addSubscription(topic, clientId);
            log.info("{} subscribed to {}", clientId, topic);
        }

        // 返回订阅确认
        ctx.writeAndFlush(createSubAck(msg.variableHeader().messageId()));
    }

    @Override
    public MqttMessageType supportedType() {
        return MqttMessageType.SUBSCRIBE;
    }
}
